package com.bw.zg2.view.activity

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bw.zg2.R
import com.bw.zg2.base.BaseActivity
import com.bw.zg2.bean.GoodsBeanItem
import com.bw.zg2.bean.SearchHistory
import com.bw.zg2.databinding.ActivitySearchBinding
import com.bw.zg2.utils.DbUtils
import com.bw.zg2.view.adapter.SearchGoodsAdapter
import com.bw.zg2.view.adapter.SearchHistoryAdapter
import com.bw.zg2.viewmodel.SearchViewModel

class SearchActivity :
    BaseActivity<SearchViewModel, ActivitySearchBinding>(R.layout.activity_search) {

    private var id: Int = 0
    private var page: Int = 1
    private var size: Int = 10
    private lateinit var adapter: SearchGoodsAdapter
    private var goodsList = mutableListOf<GoodsBeanItem>()
    override fun initData() {

        //设置列表
        viewModel.homeListLiveData.observe(this) {
            goodsList.clear()
            goodsList.addAll(it.data)
            adapter.notifyDataSetChanged()
        }

    }

    override fun initView(savedInstanceState: Bundle?) {
        viewModel.getHomeList(id, page, size)

        dataBinding.rv2.layoutManager = LinearLayoutManager(this@SearchActivity)
        adapter = SearchGoodsAdapter(this@SearchActivity, R.layout.item_search_goods_layout, goodsList)
        dataBinding.rv2.adapter = adapter


        dataBinding.searchView.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                if (!TextUtils.isEmpty(p0?.toString())) {
                    var searchHistory = SearchHistory(null, p0.toString())
                    DbUtils.shopDB.getSearchHistoryDao().insert(searchHistory)
                }
            }
        })


        dataBinding.rv1.layoutManager = GridLayoutManager(this@SearchActivity, 4)
        val searchAdapter = SearchHistoryAdapter(
            this@SearchActivity,
            R.layout.item_search_history_layout,
            DbUtils.shopDB.getSearchHistoryDao().getSearchHistory()
        )
        dataBinding.rv1.adapter = searchAdapter

    }

}